package JDBC;

import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;
public class test1 {
    public static void main(String[] args) throws SQLException {

        Scanner scanner=new Scanner(System.in);
        // 1. 创建"数据源"(DataSource)
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource) dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/java1_1?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource) dataSource).setUser("root");
        ((MysqlDataSource) dataSource).setPassword("030902");

        // 2. 和数据库服务器建立连接
        Connection connection = dataSource.getConnection();

        System.out.println("请输入学号:");
        int id=scanner.nextInt();
        System.out.println("请输入姓名:");
        String name=scanner.next();
        // 3. 构造出一个能够操作数据库的sql语句
        // String sql="insert into test values(1,'张三')";
        String sql1="insert into test values(?,?)";
        String sql2 = "update test set name='张三三' where id=1";
        String sql3="delete from test where name='张三'";
        String sql4="select * from test";
        PreparedStatement preparedStatement=connection.prepareStatement(sql1);
        preparedStatement.setInt(1,id);
        preparedStatement.setString(2,name);

        // 4. 执行sql,把刚才解析好的sql语句发给数据库服务器
        int n=preparedStatement.executeUpdate();
        System.out.println(n);

        // 5. 释放对象资源
        preparedStatement.close();
        connection.close();
    }
}
